#include "recvavpacket.h"
#include "AVPacketSerializer.h"
#include <QHostAddress>
#include <QDateTime>

RecvAVPacket::RecvAVPacket(const QString &msg, TaskType stopType, shared_ptr<RingBuffer> pSharedBuffer, QObject *parent)
    : QObject(parent)
    , _msg(msg)
    , _stopType(stopType)
    , _pTcpConnection(nullptr)
    , _pSharedBuffer(pSharedBuffer)
    , _isWorking(false)
{

}

RecvAVPacket::~RecvAVPacket()
{
    qDebug() << "lyncheer";
    this->stop();
    qDebug() << "lyncheer";
}

void RecvAVPacket::startRtmp()
{
    qDebug() << "RecvAVPacket::startRtmp()";
    _pTcpConnection = new MyTcpSocket(this);
    // 一旦TCP连接成功，就向服务器发送查看RTSP实时流的url
    connect(_pTcpConnection, &MyTcpSocket::connected, [this]() {
        qDebug() << "Tcp connected.";
        _pTcpConnection->sendTLV(TASK_GET_AVPACKET, _msg.size(), _msg.toUtf8());
    });
    // 一旦收到完整的包，就执行handleAVPacket
    connect(_pTcpConnection, &MyTcpSocket::readPacketFinished, this, &RecvAVPacket::handleAVPacket);
    connect(_pTcpConnection, &MyTcpSocket::disconnected, [this]() {
        qDebug() << "Tcp disconnected.";
//        emit sigTcpDisconnected();
    });

    _pTcpConnection->connectToHost(QHostAddress("192.168.105.108"), 8000);
    qDebug() << "111";

    _isWorking = true;
}

void RecvAVPacket::startPlayback()
{
    qDebug() << "RecvAVPacket::startPlayback()";
    _pTcpConnection = new MyTcpSocket(this);
    // 一旦TCP连接成功，就向服务器发送回放相关信息
    connect(_pTcpConnection, &MyTcpSocket::connected, [this]() {
        qDebug() << "Tcp connected.";
        _pTcpConnection->sendTLV(TASK_GET_PLAYBACK_AVPACKET, _msg.size(), _msg.toUtf8());
    });
    // 一旦收到完整的包，就执行handleAVPacket
    connect(_pTcpConnection, &MyTcpSocket::readPacketFinished, this, &RecvAVPacket::handleAVPacket);
    connect(_pTcpConnection, &MyTcpSocket::disconnected, [this]() {
        qDebug() << "Tcp disconnected.";
//        emit sigTcpDisconnected();
    });

    _pTcpConnection->connectToHost(QHostAddress("192.168.105.108"), 8000);
    qDebug() << "111";

    _isWorking = true;
}

void RecvAVPacket::handleAVPacket(Packet pkt)
{
    if (pkt._type != TASK_GET_AVPACKET_RESP_OK) {
        qWarning() << "Get AVPackt failed.";
        return;
    }

    static int totalSize = 0; // 收到的AVPacket总字节数
    static qint64 lastTime = QDateTime::currentMSecsSinceEpoch(); // 上一次的毫秒数
    static qint64 currTime = 0;
    totalSize += pkt._length;
    if (totalSize >= 50000) {
        currTime = QDateTime::currentMSecsSinceEpoch();
        double bitRate = (double)totalSize / 1024.0 * 1000 / (double)(currTime - lastTime);
        emit updateBitRate(bitRate);
        qDebug() << "totalSize:" << totalSize << ", lastTime:" << lastTime << ", currTime:" << currTime;
        qDebug() << bitRate;
        totalSize = 0;
        lastTime = currTime;
    }

    AVPacket *pPacket = AVPacketSerializer::deserialize((const uint8_t *)pkt._msg.data(), pkt._length);

    // 将avPkt存入共享缓冲区
    _pSharedBuffer->push(pPacket);

    // 在解码线程中释放pPacket
}

void RecvAVPacket::stop()
{
    _isWorking = false;
    if (_pTcpConnection && _pTcpConnection->state() == QAbstractSocket::ConnectedState) {
        _pTcpConnection->sendTLV(_stopType, 0, QByteArray());
        _pTcpConnection->close();
    }
}
